package com.motu.vertx.module.utility.webhandler;


import com.motu.vertx.module.utility.mysql.MysqlTool;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import com.motu.vertx.module.utility.webtool.Aes;
import com.motu.vertx.module.utility.webtool.BaseWebHandler;
import com.motu.vertx.module.utility.webtool.SearchCondition;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.jdbc.JDBCAuth;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.client.WebClient;
import io.vertx.sqlclient.Pool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

//import com.motu.emperor.server.game.verticle.MainVerticle;
public class ManagerHandler extends BaseWebHandler{
	private static final String tableName = "webmanager_log";
	private static final String tableNameUser = "manager_users";
	private static Pool jdbcClientWeb = null;
	private static Pool jdbcClientServer = null;
	private static JDBCAuth authProvider;
	private final static Logger logger = LoggerFactory.getLogger(ManagerHandler.class);
	public static void init(Pool jdbcWeb, Pool jdbcServer, JDBCAuth auth){
		jdbcClientWeb = jdbcWeb;
		jdbcClientServer = jdbcServer;
		authProvider = auth;
	}
	public static void list(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
		HttpServerResponse response = routingContext.response();
		String sql1 = "select count(1) from manager_users;";
		MysqlTool.queryJsonArrayFromDb(jdbcClientWeb, sql1,new JsonArray() , handler1->{
			if(handler1.succeeded()){
				JsonArray list1 = handler1.result();
				int total = list1.getJsonObject(0).getInteger("count(1)");
				String sql = "select id,username,gmname,creator,addtime FROM manager_users  order by id desc limit ?,?;";
				JsonArray params = new JsonArray();
				int pageNo = json.getInteger("pageNo");
				int pageSize = json.getInteger("pageSize");
				int start = pageNo*pageSize;
				params.add(start);
				params.add(pageSize);
				MysqlTool.queryJsonArrayFromDb(jdbcClientWeb, sql,params , handler->{
					if(handler.succeeded()){
						JsonArray list = handler.result();
						JsonObject result = new JsonObject();
						result.put("total", total);
						result.put("rows",list);
						sendHttpResponse(response, result);
					}else{
						logger.error(handler.cause().getMessage());
						sendHttpResponseError(response, "数据库查询失败，请稍后重试！");
					}
				});
			}else{
				logger.error(handler1.cause().getMessage());
				sendHttpResponseError(response, "数据库查询失败，请稍后重试！");
			}
		});
	}
	
	/*
	 * 新增账号
	 */
	public static void add(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
		logger.debug("addOneManager");
		HttpServerResponse response = routingContext.response();
		String username = json.getString("name");
		String password = Aes.getDecryptPwd(json.getString("pwd"));
		String gmname = json.getString("gmname");
		String webperms = json.getString("webperms");
		String bigames = json.getString("bigames");
		String gameperms = json.getString("gameperms");
		String platform = json.getString("platform");
		String channel = json.getString("channel");
		int account_type = json.getInteger("account_type");
		int depId = json.getInteger("depid");
		String birthday = json.getString("birthday");
		int gender = json.getInteger("gender");
		String snack_phone = json.getString("snack_phone");
		String creator = adminName;
		String sql1 = "select 1 from  manager_users where username = ?;";
		JsonArray params1 = new JsonArray();
		params1.add(username);
		MysqlTool.queryJsonArrayFromDb(jdbcClientWeb, sql1, params1, res->{
			if(res.succeeded()){
				if(res.result().size() == 0){
					String pwd_salt = authProvider.generateSalt();
					String password2 = authProvider.computeHash(password, pwd_salt);
					String sql = "insert into manager_users(username,gmname,employeeid,depid,groupid,password,password_salt,creator,addtime,webperms,bigames,gameperms,platform,channel,account_type,birthday,gender,snack_phone) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
					JsonArray params = new JsonArray();
					params.add(username);
					params.add(gmname);
					params.add(json.getInteger("employeeid"));
					params.add(depId);
					params.add(json.getInteger("groupid"));
					params.add(password2);
					params.add(pwd_salt);
					params.add(creator);
					params.add(TimeUtils.getCurTime());
					params.add(webperms);
					params.add(bigames);
					params.add(gameperms);
					params.add(platform);
					params.add(channel);
					params.add(account_type);
					params.add(birthday);
					params.add(gender);
					params.add(snack_phone);


					MysqlTool.updateToDb(jdbcClientWeb, sql, params, handler->{
						if (handler.succeeded()){
							JsonObject result = new JsonObject();
							sendHttpResponse(response, result);
							logger.debug("addOneManager ok");
						} else {
							logger.error(handler.cause().getMessage());
							sendHttpResponseError(response, "数据库插入失败，请稍后重试！");
						}
					});
				} else {
					sendHttpResponseError(response, "账号名已存在！");
				}
			} else {
				sendHttpResponseError(response, res.cause().getMessage());
			}
		});
	}
	
	/**
	 * 查询
	 * @param routingContext
	 * @param json
	 * @param adminName
	 */
	public static void search(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
		List<SearchCondition> scList = new ArrayList<SearchCondition>();
		scList.add(new SearchCondition("name", "like", new String[]{"username", "gmname"}, null));
		scList.add(new SearchCondition("depid", "=", null, null));
		searchFromTable(routingContext, jdbcClientWeb, json, tableNameUser, scList);
	}
	
	/**
	 * 获取用户信息
	 * @param routingContext
	 * @param json
	 * @param adminName
	 */
	public static void get(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
		HttpServerResponse response = routingContext.response();
		int id = json.getInteger("id");
		String sql = "select id,username,gmname,creator,depid,groupid,addtime,webperms,bigames,relation,email,employeeid,gameperms,platform,channel,account_type,birthday,gender,snack_phone FROM manager_users where id = ?;";
		JsonArray params = new JsonArray();
		params.add(id);
		MysqlTool.queryJsonArrayFromDb(jdbcClientWeb, sql, params, handler->{
			if(handler.succeeded()){
				JsonArray list = handler.result();
				if(list.size() == 1){
					String sql2 =  "select role FROM manager_roles where username = ?;";
					JsonArray params2 = new JsonArray();
					JsonObject obj = list.getJsonObject(0);
					params2.add(obj.getString("username"));
					MysqlTool.queryJsonArrayFromDb(jdbcClientWeb, sql2, params2, handler2->{
						if(handler2.succeeded()){
							JsonArray list2 = handler2.result();
							JsonArray list3 = new JsonArray();
							if(list2 != null){
								for(int i=0;i<list2.size();i++){
									list3.add(list2.getJsonObject(i).getString("role"));
								}
							}
							JsonObject result = new JsonObject();
							obj.put("roles", list3);
							result.put("info",obj);
							sendHttpResponse(response, result);
						}else{
							logger.error(handler2.cause().getMessage());
							sendHttpResponseError(response, "数据库查询失败，请稍后重试！");
						}
					});

				}else{
					sendHttpResponseError(response, "数据库查询失败，请输入有效的id！");
				}

			}else{
				logger.error(handler.cause().getMessage());
				sendHttpResponseError(response, "数据库查询失败，请稍后重试！");
			}
		});
	}
	
	/**
	 * 修改账号信息
	 * @param routingContext
	 * @param json
	 * @param adminName
	 */
	public static void update(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
		logger.debug("updateOneManager");
		updateToTable(routingContext, jdbcClientWeb, tableNameUser, json);

	}
	
	/**
	 * 删除账号
	 * @param routingContext
	 * @param json
	 * @param adminName
	 */
	public static void delete(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
		HttpServerResponse response = routingContext.response();
		String username  = json.getString("name");
		String curname = adminName;
		if(username.equalsIgnoreCase(curname)){
			sendHttpResponseError(response, "不能删除自己！");
			return;
		}

		String sql = "delete from manager_users  where username = ?;";
		JsonArray params = new JsonArray();

		params.add(username);

		MysqlTool.updateToDb(jdbcClientWeb, sql, params, handler->{
			if(handler.succeeded()){
				String sql2 = "delete from manager_roles where username = ?";
				MysqlTool.updateToDb(jdbcClientWeb, sql2, params, handler2->{
					if(handler2.failed()){
						logger.error(handler2.cause().getMessage());
					}
				});
				JsonObject result = new JsonObject();

				sendHttpResponse(response, result);
				
				//删除webpages_username表的记录
				String sql3 = "delete from webpages_username where username = ?";
				MysqlTool.updateToDb(jdbcClientWeb, sql3, params, handler2->{});
			}else{
				logger.error(handler.cause().getMessage());
				sendHttpResponseError(response, "数据库更新失败，请稍后重试！");
			}
		});

	}
	
	/**
	 * 重置密码
	 * @param routingContext
	 * @param json
	 * @param adminName
	 */
	public static void resetpwd(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
		HttpServerResponse response = routingContext.response();
		int id = json.getInteger("id");
		String password = Aes.getDecryptPwd(json.getString("pwd"));
		String pwd_salt = authProvider.generateSalt();
		password = authProvider.computeHash(password, pwd_salt);
		String sql = "update manager_users set password = ?,password_salt = ? where id = ?;";
		JsonArray params = new JsonArray();

		params.add(password);
		params.add(pwd_salt);
		params.add(id);

		MysqlTool.updateToDb(jdbcClientWeb, sql, params, handler->{
			if(handler.succeeded()){

				JsonObject result = new JsonObject();

				sendHttpResponse(response, result);
			}else{
				logger.error(handler.cause().getMessage());
				sendHttpResponseError(response, "数据库更新失败，请稍后重试！");
			}
		});
	}
	
	/**
	 * 修改密码
	 * @param routingContext
	 * @param json
	 * @param adminName
	 */
	public static void user_changepwd(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
		HttpServerResponse response = routingContext.response();
		String curname = adminName;
		String pwd  = Aes.getDecryptPwd(json.getString("pwd"));
		String newpwd =  Aes.getDecryptPwd(json.getString("newpwd"));
		JsonObject authInfo = new JsonObject().put("username", curname).put("password", pwd);
		authProvider.authenticate(authInfo, auRes->{
			if(auRes.succeeded() ){
				String pwd_salt = authProvider.generateSalt();
				String password = authProvider.computeHash(newpwd, pwd_salt);
				String sql = "update manager_users set password = ?,password_salt = ? where username = ?;";
				JsonArray params = new JsonArray();
				params.add(password);
				params.add(pwd_salt);
				params.add(curname);

				MysqlTool.updateToDb(jdbcClientWeb, sql, params, handler->{
					if(handler.succeeded()){

						JsonObject result = new JsonObject();

						sendHttpResponse(response, result);
					}else{
						logger.error(handler.cause().getMessage());
						sendHttpResponseError(response, "数据库更新失败，请稍后重试！");
					}
				});
			}else{
				logger.error(auRes.cause().getMessage());
				sendHttpResponseError(response, "密码验证失败，请重新输入！");
			}
		});
	}
	
	/**
	 * 删除账号权限角色
	 * @param routingContext
	 * @param json
	 * @param adminName
	 */
	public static void user_delrole(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
		HttpServerResponse response = routingContext.response();
		String username  = json.getString("name");
		String role  = json.getString("role");

		String sql = "delete from manager_roles  where username = ? and role = ?;";
		JsonArray params = new JsonArray();

		params.add(username);
		params.add(role);

		MysqlTool.updateToDb(jdbcClientWeb, sql, params, handler->{
			if(handler.succeeded()){
				JsonObject result = new JsonObject();

				sendHttpResponse(response, result);
			}else{
				logger.error(handler.cause().getMessage());
				sendHttpResponseError(response, "数据库删除失败，请稍后重试！");
			}
		});
	}
	
	/**
	 * 添加角色权限
	 * @param routingContext
	 * @param json
	 * @param adminName
	 */
	public static void user_addrole(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
		logger.debug("addUserRole");
		HttpServerResponse response = routingContext.response();
		String username = json.getString("name");
		String role = json.getString("role");
		String sql = "insert into manager_roles(username,role) values(?,?);";
		JsonArray params = new JsonArray();
		params.add(username);
		params.add(role);
		MysqlTool.updateToDb(jdbcClientWeb, sql, params, handler->{
			if (handler.succeeded()){
				JsonObject result = new JsonObject();
				sendHttpResponse(response, result);
				logger.debug("addUserRole ok");
			} else {
				logger.error(handler.cause().getMessage());
				sendHttpResponseError(response, "数据库插入失败，请稍后重试！");
			}
		});
	}

	public static void log_list(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
		getTableList(routingContext,jdbcClientServer,tableName);
	}


	public static void log_search(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
		
		List<SearchCondition> scList = new ArrayList<SearchCondition>();
		scList.add(new SearchCondition("api", "like", null, null));
		scList.add(new SearchCondition("user", "=", null, null));
		
		searchFromTable(routingContext, jdbcClientServer, json, tableName, scList);
	}
	
	/**
	 * 查询后台地址
	 * @param routingContext
	 * @param json
	 * @param adminName
	 */
	public static void searchWeb(RoutingContext routingContext, JsonObject json,String adminName,WebClient client) {
		List<SearchCondition> scList = new ArrayList<>();
		scList.add(new SearchCondition("projectid", "=", null, null));
		scList.add(new SearchCondition("name", "like", null, null));
		scList.add(new SearchCondition("ip", "like", null, null));
		scList.add(new SearchCondition("ids", "in", new String[] {"id"}, json.getJsonArray("ids")));
		searchFromTable(routingContext, jdbcClientWeb, json, "webtype", scList);
	}
	
	/**
	 * 新增后台地址
	 * @param routingContext
	 * @param json
	 * @param adminName
	 */
	public static void addWeb(RoutingContext routingContext, JsonObject json,String adminName,WebClient client) {
		addToTable(routingContext, jdbcClientWeb, "webtype", null);
	}
	
	/**
	 * 修改后台地址
	 * @param routingContext
	 * @param json
	 * @param adminName
	 */
	public static void updateWeb(RoutingContext routingContext, JsonObject json,String adminName,WebClient client) {
		updateToTable(routingContext, jdbcClientWeb, "webtype", null);
	}
	
	/**
	 * 获取一条后台地址信息
	 * @param routingContext
	 * @param json
	 * @param adminName
	 */
	public static void getoneWeb(RoutingContext routingContext, JsonObject json,String adminName,WebClient client) {
		HttpServerResponse response = routingContext.response();
		long id = json.getLong("id");
		String sql = "select * from webtype where id=?;";
		JsonArray params = new JsonArray();
		params.add(id);
		MysqlTool.queryJsonArrayFromDb(jdbcClientWeb, sql, params, handler->{
			if (handler.succeeded()) {
				JsonArray list = handler.result();
				JsonObject obj = list.getJsonObject(0);
				JsonObject result = new JsonObject();
				result.put("info", obj);
				sendHttpResponse(response, result);
			} else {
				logger.error(handler.cause().getMessage());
				sendHttpResponseError(response, "数据库查询失败，请稍后重试！");
			}
		});
	}
	
	/**
	 * 删除一条后台地址信息
	 * @param routingContext
	 * @param json
	 * @param adminName
	 */
	public static void deleteWeb(RoutingContext routingContext, JsonObject json,String adminName,WebClient client) {
		deleteFromTable(routingContext, jdbcClientWeb, "webtype");
	}
}
